import schedule from 'node-schedule'
import fs from 'fs'
import mongoose from 'mongoose'
import path from 'path'
import '../mongodb'

const Info = mongoose.model('Info')

export const scheduleCronstyle = () => {
  // 每天的凌晨1点1分30秒触发
  schedule.scheduleJob('30 1 1 * * *', () => {
    deleteFiles(path.resolve(__dirname, '../static/uploads'))
  })
}

async function deleteFiles(path) {
  console.log('开始删除')
  if (fs.existsSync(path)) {
    let files = []
    files = fs.readdirSync(path)
    const infos = await Info.find({}).exec()
    const urls = infos.map(model => {
      const url = model._doc.url || ''
      return url.substring(0, url.lastIndexOf('.')) || ''
    })

    files.forEach(function(file) {
      const tmp = file.substring(0, file.lastIndexOf('.'))
      if (urls.indexOf(tmp) < 0) {
        const curPath = path + '/' + file
        console.log('执行删除')
        console.log(curPath)
        fs.unlinkSync(curPath)
      }
    })
  }
}
